package com.yuliang.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;



import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

import java.io.ByteArrayInputStream;

import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.ByteArrayInputStream;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import com.yuliang.domain.R;
import com.yuliang.enums.AppHttpCodeEnum;
import com.yuliang.exception.SystemException;
import com.yuliang.service.UploadService;
import com.yuliang.utils.PathUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;


@Service
@Data
@ConfigurationProperties(prefix = "alioss")  //yml文件
public class UploadServiceImpl implements UploadService {

    //七牛云
    private String accessKey;
    private String secretKey;

    private String accessKeyId;
    private String accessKeySecret;
    private String bucket;
    private String preUrl;


    @Override
    public R uploadImg(MultipartFile img) throws com.aliyuncs.exceptions.ClientException {
        String originalFilename = img.getOriginalFilename();
        //判断文件类型
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        //上传文件
        //文件名要求 "yyyy/mm/dd/uuid+.(文件格式)"
        String fileName = PathUtils.generateFilePath(originalFilename);
        String url = uploadOOS(img, fileName);
        return R.okResult(url);//要求返回文件的url地址
    }


    public String uploadOOS(MultipartFile img,String fileName)  {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 代码嵌入
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "liangyu-blog";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            // 填写Byte数组。
            byte[] content = img.getBytes();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));

            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //返回文件地址
            return "https://liangyu-blog.oss-cn-beijing.aliyuncs.com/"+putObjectRequest.getKey();
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "error";
    }


    //七牛云
//    public String uploadOOS(MultipartFile img,String fileName) {
//
//        //构造一个带指定 Region 对象的配置类
//        Configuration cfg = new Configuration(Region.autoRegion());
//        //...其他参数参考类注释
//        UploadManager uploadManager = new UploadManager(cfg);
//
//        //默认不指定key的情况下，以文件内容的hash值作为文件名
//        String key = fileName;
//
//        try {
//            InputStream inputStream = img.getInputStream();
//            Auth auth = Auth.create(accessKey, secretKey);
//            String upToken = auth.uploadToken(bucket);
//
//            try {
//                Response response = uploadManager.put(inputStream, key, upToken, null, null);
//                //解析上传成功的结果
//                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//                System.out.println(putRet.key);//文件名
//                System.out.println(putRet.hash);//文件名的哈希值
//                return preUrl + key;
//            } catch (QiniuException ex) {
//                ex.printStackTrace();
//                if (ex.response != null) {
//                    System.err.println(ex.response);
//                    try {
//                        String body = ex.response.toString();
//                        System.err.println(body);
//                    } catch (Exception ignored) {
//                    }
//                }
//            }
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return "error";
//    }
}

